<?php

namespace app\common\model;

use app\admin\model\ConfigValueModel;
use think\Model;
use traits\model\SoftDelete;

/**
 * @brief   合同
 * @param
 * @return
 * @author wanchengniuniu
 * @date 2025/2/27
 *
 */
class Contract extends Model
{
    use SoftDelete;

    // 表名
    protected $name = 'user_contract';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    const STATUS_NORMAL = 1;//已签
    const STATUS_DEFAULT = 0;//未签
    const STATUS_OVERDUE = 2;//过期

    static public function getStatusList($type = 2, $value = 1)
    {
        $data = [
            self::STATUS_DEFAULT => '待审',
            self::STATUS_NORMAL => '正常',
            self::STATUS_OVERDUE => '过期',
        ];
        if ($type == 1) {
            return $data[$value] ?? '';
        } else {
            return $data;
        }
    }

    static public function getYaTypeList($type = 2, $value = 1)
    {
        $data = ConfigValueModel::where(['cid' => 7])->column('option_name', 'id');
        if ($type == 1) {
            return $data[$value] ?? '';
        } else {
            return $data;
        }
    }

    public function building()
    {
        return $this->belongsTo('app\admin\model\BuildingModel', 'build_id', 'id');
    }

    public function room()
    {
        return $this->belongsTo('app\admin\model\BuildingRoomModel', 'room_id', 'id');
    }

    public function house()
    {
        return $this->belongsTo('app\admin\model\HouseModel', 'house_id', 'id');
    }


    public function board()
    {
        return $this->hasMany('app\admin\model\ContractBoardModel', 'contract_id', 'id');
    }

    public function fixed()
    {
        return $this->hasMany('app\admin\model\ContractFixedModel', 'contract_id', 'id');
    }

    public function pt()
    {
        return $this->hasMany('app\admin\model\ContractPtModel', 'contract_id', 'id');
    }

    public function delUser()
    {
        return $this->belongsTo(User::class, 'del_uid', 'id')->bind('username');
    }

    public function createUser()
    {
        return $this->belongsTo(User::class, 'create_user_id', 'id')->field('id,username');
    }


    protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function getDeleteTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['deletetime'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

}
